var id = 0;

function extract_params( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
	return "";
	else
	return results[1];
}

function getManualActivityId(parentRow){
	var id = parentRow.children('.checkbox').eq(0).find("input").val();	
	return id;
}

function editManualEntry(obj){
	var parentRow = $(obj).closest('tr');
	id = getManualActivityId(parentRow);
	$.get('summaries/get_manual_entry_info', { activity_id: id}, function(data) {
		var entry = jQuery.parseJSON(data).entry;
		var desc = entry.activity
		var day = entry.day
		var duration = entry.finish - entry.start	
		var hours = Math.floor(duration / (60 * 60));
		var divisor_for_minutes = duration % (60 * 60);
		var minutes = Math.floor(divisor_for_minutes / 60);
		$("#manual_entry_title").val(desc);
		$("#edit_entry_datepicker").val(day);
		$("#manual_entry_hours").val(hours);
		$("#manual_entry_mins").val(minutes);
		$('#edit_entry_modal').jqmShow();
	});
}


function addParams(obj,key,value){
	obj[key] = value;
	return obj;
}

function addDateParametersToPostArray(postParams){
	postParams = addParams(postParams,'start',extract_params( 'start'));
	postParams['start'] = extract_params( 'start');
	if (extract_params( 'range') != "")
	postParams = addParams(postParams,'range',extract_params( 'range'));
	else if (extract_params( 'end') != "")
	postParams = addParams(postParams,'end',extract_params( 'end'));
	return postParams;
}

function updateManualEntryinDB(){
	title = $("#manual_entry_title").val();
	date = $("#edit_entry_datepicker").val();
	hours = $("#manual_entry_hours").val();
	minutes = $("#manual_entry_mins").val();
	var postParams = {};
	postParams = addDateParametersToPostArray(postParams);
	postParams = addParams(postParams,'title',title);
	postParams = addParams(postParams,'activity_id',id);
	postParams = addParams(postParams,'hours',hours);
	postParams = addParams(postParams,'mins',minutes);
	postParams = addParams(postParams,'date',date);
	$.post('/summaries/ajax_edit_manual_entry',postParams, null, 'script');	
}
